﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.SessionState;
using Bilylib;
using System.Data;
using System.Configuration;
using System.Drawing;

public partial class sitemanagement_HTLogin : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    private string nameUser = "";
    private string role = "";
    private string avatar = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["Username"] != null)
            {
                Response.Redirect("Default.aspx");
            }

            try
            {
                if (Request.Cookies["HoangThinhCookie"] != null)
                {
                    HttpCookie myCookie = Request.Cookies.Get("HoangThinhCookie");
                    string user = myCookie.Values["Username"].ToString();
                    string pass = myCookie.Values["Password"].ToString();

                    if (CheckLogin(user, pass))
                    {
                        if (Application["ses"] != null)
                        {
                            ((HttpSessionState)Application["ses"]).Clear();
                        }

                        if (role == "Admin")
                        {
                            Session["Role"] = "1";
                        }
                        else if (role == "Director")
                        {
                            Session["Role"] = "2";
                        }
                        Session["Username"] = user;
                        Session["Name"] = nameUser;
                        Application["ses"] = Session;

                        Response.Redirect(Request.RawUrl);
                    }
                    else
                    {
                        lblMsg.ForeColor = ColorTranslator.FromHtml("Red");
                        lblMsg.Text = "Cookie lỗi, đăng nhập lại !";
                    }
                }
            }
            catch
            {
                lblMsg.ForeColor = ColorTranslator.FromHtml("Red");
                lblMsg.Text = "Lỗi cookie !";
            }

            username.Focus();
        }

        try
        {
            if (Application["ses"] != null)
            {
                lblMsg.ForeColor = ColorTranslator.FromHtml("Red");
                lblMsg.Text = "Tài khoản này đang được sử dụng !";
            }
        }
        catch { }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Encrypt encrypt = Encrypt.newInstance();
        string pass = encrypt.EncryptString(password.Value, "hoangthinh");
        string user = username.Value;

        try
        {
            if (CheckLogin(user, pass))
            {
                if (Application["ses"] != null)
                {
                    ((HttpSessionState)Application["ses"]).Clear();
                }

                if (role == "Admin")
                {
                    Session["Role"] = "1";
                }
                else if (role == "Director")
                {
                    Session["Role"] = "2";
                }
                else
                {
                    Session["Role"] = "3";
                }
                Session["LastLog"] = DateTime.Now.ToString("dd/MM/yyyy hh:mm");
                Session["Avatar"] = avatar;
                Session["Username"] = user;
                Session["Name"] = nameUser;
                Application["ses"] = Session;

                if (chkRemember.Checked)
                {
                    HttpCookie myCookie = new HttpCookie("HoangThinhCookie");
                    Response.Cookies.Remove("HoangThinhCookie");
                    Response.Cookies.Add(myCookie);
                    myCookie.Values.Add("Username", user);
                    myCookie.Values.Add("Password", pass);
                    myCookie.Values.Add("Name", nameUser);
                    myCookie.Values.Add("Avatar", avatar);
                    myCookie.Values.Add("LastLog", DateTime.Now.ToString("dd/MM/yyyy hh:mm"));
                    DateTime dtExpiry = DateTime.Now.AddMonths(1);
                }

                Response.Redirect("Default.aspx");
            }
            else
            {
                lblMsg.ForeColor = ColorTranslator.FromHtml("Red");
                lblMsg.Text = "Tài khoản không đúng !";
            }
        }
        catch
        {
            lblMsg.ForeColor = ColorTranslator.FromHtml("Red");
            lblMsg.Text = "Lỗi đăng nhập !";
        }
    }

    public bool CheckLogin(string username, string password)
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["HoangThinhDataConnectionString"].ConnectionString;
        cmd.Connection = conn;
        cmd.CommandText = "SELECT Users.*, Roles.RoleID, Roles.RoleName FROM Roles INNER JOIN Users ON Roles.RoleID = Users.IDRole";
        cmd.CommandType = CommandType.Text;
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                if (username == reader["UserID"].ToString() && password == reader["Password"].ToString() && bool.Parse(reader["Status"].ToString()) == true)
                {
                    nameUser = reader["UserID"].ToString();
                    role = reader["RoleName"].ToString();
                    avatar = reader["ImageUrl"].ToString();
                    return true;
                }
            }
        }
        conn.Close();

        return false;
    }

    protected void btnReg_Click(object sender, EventArgs e)
    {
        Response.Redirect("HTForgot.aspx");
    }
}